package system_object_dao

import (
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/util/pointer"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
	"time"
)

func (cls *SystemObject) SaveSystemObject(ctx context.Context, systemObject *model.SystemObject) errors.Error {
	if nil == systemObject {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDSO_CT.SO_CT.SSO_CT.150357 systemObject is nil")

		return errors.ErrorServerInternalError("IDSO_CT.SO_CT.SSO_CT.170357", "异常的传入参数")
	}

	systemObject.UpdateTime = pointer.New(time.Now().Unix())
	if nil == systemObject.CreateTime || 0 == *systemObject.CreateTime {
		systemObject.CreateTime = pointer.New(time.Now().Unix())

		if err := cls.GetDb(ctx).Model(new(model.SystemObject)).Create(&systemObject).Error; nil != err {
			logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDSO_CT.SO_CT.SSO_CT.250357 create systemObject failed, err %v", err)

			return errors.ErrorServerInternalError("IDSO_CT.SO_CT.SSO_CT.270357", "创建数据失败")
		}

		return nil
	}

	if err := cls.GetDb(ctx).Model(new(model.SystemObject)).Where("id = ?", systemObject.Id).Updates(&systemObject).Error; nil != err {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDSO_CT.SO_CT.SSO_CT.340357 save systemObject failed, err %v", err)

		return errors.ErrorServerInternalError("IDSO_CT.SO_CT.SSO_CT.360357", "更新数据失败")
	}

	return nil
}
